package com.lz.sports.storage

import android.hardware.usb.UsbDevice
import com.github.mjdev.libaums.UsbMassStorageDevice
import com.github.mjdev.libaums.fs.UsbFile
import java.io.File

class UsbStorageDevice(private val device: UsbMassStorageDevice) {

    companion object {

        fun usbPath(usbFile: UsbFile): String {
            val sb = StringBuilder(File.separator).append(usbFile.name)
            var parent = usbFile.parent
            while (parent != null) {
                parent.name.takeIf { it != "" }?.also { sb.insert(0, it).insert(0, File.separatorChar) }
                parent = parent.parent
            }
            return sb.toString()
        }
    }

    private var hasInit: Boolean = false

    private fun openDevice() {
        if (!hasInit) {
            hasInit = true
            device.init()
        }
    }

    //关闭
    @Synchronized
    fun close() {
        if (hasInit) {
            try {
                device.close()
            } catch (_: Exception) {
            }
        }
    }

    @Synchronized
    fun rootDir(): UsbFile? {
        openDevice()
        return device.partitions[0].fileSystem?.rootDirectory
    }

    fun getDevice(): UsbDevice = device.usbDevice
}